package org.cboard.dto;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import org.cboard.query.JsonParseUtils;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

public class WidgetLinkBase implements Serializable {
    private static final long serialVersionUID = 5959684659926461306L;

    /**
     * 联动者传出参数（可以多个）以逗号隔开
     */
    private String activeWidgetConfig;

    /**
     * 被联动者联动项目(至少一个)
     */
    private String passiveWidgetConfig;

    public String getActiveWidgetConfig() {
        return activeWidgetConfig;
    }

    public void setActiveWidgetConfig(String activeWidgetConfig) {
        this.activeWidgetConfig = activeWidgetConfig;
    }

    public String getPassiveWidgetConfig() {
        return passiveWidgetConfig;
    }

    public void setPassiveWidgetConfig(String passiveWidgetConfig) {
        this.passiveWidgetConfig = passiveWidgetConfig;
    }

    /**
     * WidgetLinkParam
     *
     * @param json widget.data_json
     * @return
     */
    public Map<String, String> getParams(String json, WidgetLinkParam ac) {
        Map<String, String> res = getActiveWidgetCols(json, ac);
        Map<String, String> map = Maps.newHashMap();
        if (passiveWidgetConfig != null) {
            StringBuilder sb = new StringBuilder();
            List<WidgetLinkParam> list = JSONObject.parseArray(passiveWidgetConfig, WidgetLinkParam.class);
            for (WidgetLinkParam wp : list) {
                if (res.containsKey(wp.getCol())) {
                    map.put(wp.getCol(), res.get(wp.getCol()));
                }
            }
        }
        return res;
    }

    /**
     * 前台传过来永远只有一个类似 {
     * "widgetId": 8,
     * "col": "a-b-c-d"  //ps:这个匹配 联动图表的维度
     * }
     *
     * @return
     */
    public Map<String, String> getActiveWidgetCols(String json, WidgetLinkParam ac) {
        if (activeWidgetConfig != null) {
            String cols[] = ac.getCol().split("-");
            List<WidgetLinkParam> list = JsonParseUtils.parseJson(JSONObject.parseObject(json).getJSONObject("config").getString("keys"), WidgetLinkParam.class);
            Map<String, String> map = Maps.newHashMap();
            for (int i = 0; i < list.size(); i++) {
                WidgetLinkParam o = list.get(i);
                map.put(o.getCol(), cols[i]);
            }
            return map;
        }
        return null;
    }


}
